package com.freight.order.serviceimpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freight.base.entity.Area;
import com.freight.base.mapper.AreaCityMapper;
import com.freight.base.utils.AreaAddressUtil;
import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.redis.RedisTemplateHelper;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.common.vo.SearchVo;
import com.freight.core.entity.User;
import com.freight.core.service.OperationLogService;
import com.freight.core.service.UserService;
import com.freight.file.constants.FileConstant;
import com.freight.file.service.FileService;
import com.freight.msg.service.MessageSendService;
import com.freight.msg.service.MessageService;
import com.freight.order.dao.*;
import com.freight.order.dto.*;
import com.freight.order.entity.*;
import com.freight.order.enums.OrderStatusEnum;
import com.freight.order.mapper.*;
import com.freight.order.service.*;
import com.freight.order.vo.*;

import com.freight.user.dao.VehicleLicenseDao;
import com.freight.user.entity.*;
import com.freight.user.mapper.DriverVoMapper;
import com.freight.user.mapper.VehicleVoMapper;
import com.freight.user.util.GpsUtil;
import com.freight.user.util.UserDtoUtils;
import com.freight.user.vo.VehicleGpalInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 货物续期需求接口实现
 *
 * @author huyingtai
 */
@Slf4j
@Service
public class OrderOrderServiceImpl implements OrderOrderService {

    @Autowired
    private OrderOrderDao orderOrderDao;

    @Autowired
    private OrderMainMapper orderMainMapper;

    @Autowired
    private QuotationRecordDao quotationRecordDao;

    @Autowired
    private MobileTrackDao mobileTrackDao;

    @Autowired
    private OrderEntrustedMapper orderEntrustedMapper;

    @Autowired
    private MessageService messageService;

    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    private MessageSendService messageSendService;

    @Autowired
    private VehicleLicenseDao vehicleLicenseDao;

    @Autowired
    private QuotationRecordMapper quotationRecordMapper;

    @Autowired
    private AreaAddressUtil areaAddressUtil;



    @Autowired
    private FileService fileService;

    @Autowired
    private DriverVoMapper driverVoMapper;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private OrderGoodsDao orderGoodsDao;

    @Autowired
    private OrderExtendDao orderExtendDao;

    @Autowired
    private GoodsLoadingTimeDao goodsLoadingTimeDao;

    @Autowired
    private DocumentaryDao documentaryDao;

    @Autowired
    private RedisTemplateHelper redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private VehicleVoMapper vehicleVoMapper;

    @Autowired
    private AreaCityMapper areaCityMapper;

    @Autowired
    private OrderGoodsVoMapper orderGoodsVoMapper;

    private GpsUtil gpsUtil = new GpsUtil();

    private static double EARTH_RADIUS = 6371.393;

    @Override
    public OrderOrderDao getRepository() {
        return orderOrderDao;
    }

    @Override
    public void updateAddressFence(String addressFence, Long orderId) {
        OrderOrder order = orderOrderDao.getOne(orderId);
        if(order!=null){
            order.setAddressFence(addressFence);
            orderOrderDao.save(order);
        }

    }

    @Override
    public JSONArray vehicleListDispatch(Long goodsId, String goodsTypae, String goodsSubTypae, String vehicleState,String range) {
        JSONArray jsonArray = new JSONArray();
        String [] goodsSubTypaes = null;
        if(goodsSubTypae!=null && !goodsSubTypae.equals("")){
            goodsSubTypaes = goodsSubTypae.split(",");
        }
        List gpsList = vehicleVoMapper.vehicleGoodsType(goodsTypae, goodsSubTypaes, vehicleState);
        OrderGoods orderGoods = orderGoodsDao.getOne(goodsId);
        if(gpsList!=null && gpsList.size()>0){
            JSONObject data = new JSONObject();
            data.put("deviceids",gpsList);
            data.put("lastquerypositiontime",0);
            JSONObject requestJson = gpsUtil.gpsPost(data,"action=lastposition&",redisTemplate);
            if(requestJson!=null && requestJson.getInteger("status")==0){
                JSONArray recordsArray = requestJson.getJSONArray("records");
                if(recordsArray!=null&&recordsArray.size()>0){
                    for (int i = 0; i< recordsArray.size(); i++) {
                        JSONObject json = recordsArray.getJSONObject(i);
                        if(range == null){
                            JSONObject returnJson = new JSONObject();
                            returnJson.put("lat",json.getDouble("callat"));
                            returnJson.put("lon",json.getDouble("callon"));
                            returnJson.put("gpsEquipment",json.getString("deviceid"));

                            VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(json.getString("deviceid"));

                            Double goodWeight = vehicleVoMapper.getVehicleGpalOrder(vehicleGpalInfoVo.getVehicleId());

                            if(goodWeight!=null && goodWeight>0){
                                returnJson.put("taskState","1");
                            }else {
                                returnJson.put("taskState","0");
                            }

                            returnJson.put("vehicleNum",vehicleGpalInfoVo.getVehicleNum());
                            jsonArray.add(returnJson);

                        }else {
                            double callat = json.getDouble("callat");
                            double callon = json.getDouble("callon");
                            boolean b =distanceCalculation(orderGoods.getBeginLat(),orderGoods.getBeginLng(),callat,callon,Double.valueOf(range) * 1000);
                            if(b){
                                JSONObject returnJson = new JSONObject();
                                returnJson.put("lat",json.getDouble("callat"));
                                returnJson.put("lon",json.getDouble("callon"));
                                returnJson.put("gpsEquipment",json.getString("deviceid"));
                                VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(json.getString("deviceid"));

                                Double goodWeight = vehicleVoMapper.getVehicleGpalOrder(vehicleGpalInfoVo.getVehicleId());

                                if(goodWeight!=null && goodWeight>0){
                                    returnJson.put("taskState","1");
                                }else {
                                    returnJson.put("taskState","0");
                                }
                                returnJson.put("vehicleNum",vehicleGpalInfoVo.getVehicleNum());
                                jsonArray.add(returnJson);
                            }
                        }
                    }
                }
            }
        }
        return jsonArray;
    }

    @Override
    public JSONArray companyVehicleListDispatch(Long goodsId, String goodsTypae, String goodsSubTypae, String vehicleState,String range) {
        User u = securityUtil.getCurrUser();

        JSONArray jsonArray = new JSONArray();
        String [] goodsSubTypaes = null;
        if(goodsSubTypae!=null && !goodsSubTypae.equals("")){
            goodsSubTypaes = goodsSubTypae.split(",");
        }
        List gpsList = vehicleVoMapper.companyVehicleListPosition(goodsTypae, goodsSubTypaes, vehicleState, u.getId());
        OrderGoods orderGoods = orderGoodsDao.getOne(goodsId);
        if(gpsList!=null && gpsList.size()>0){
            JSONObject data = new JSONObject();
            data.put("deviceids",gpsList);
            data.put("lastquerypositiontime",0);
            JSONObject requestJson = gpsUtil.gpsPost(data,"action=lastposition&",redisTemplate);
            if(requestJson!=null && requestJson.getInteger("status")==0){
                JSONArray recordsArray = requestJson.getJSONArray("records");
                if(recordsArray!=null&&recordsArray.size()>0){
                    for (int i = 0; i< recordsArray.size(); i++) {
                        JSONObject json = recordsArray.getJSONObject(i);
                        if(range == null){
                            JSONObject returnJson = new JSONObject();
                            returnJson.put("lat",json.getDouble("callat"));
                            returnJson.put("lon",json.getDouble("callon"));
                            returnJson.put("gpsEquipment",json.getString("deviceid"));
                            VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(json.getString("deviceid"));

                            Double goodWeight = vehicleVoMapper.getVehicleGpalOrder(vehicleGpalInfoVo.getVehicleId());

                            if(goodWeight!=null && goodWeight>0){
                                returnJson.put("taskState","1");
                            }else {
                                returnJson.put("taskState","0");
                            }
                            returnJson.put("vehicleNum",vehicleGpalInfoVo.getVehicleNum());
                            jsonArray.add(returnJson);

                        }else {
                            double callat = json.getDouble("callat");
                            double callon = json.getDouble("callon");
                            boolean b =distanceCalculation(orderGoods.getBeginLat(),orderGoods.getBeginLng(),callat,callon,Double.valueOf(range) * 1000);
                            if(b){
                                JSONObject returnJson = new JSONObject();
                                returnJson.put("lat",json.getDouble("callat"));
                                returnJson.put("lon",json.getDouble("callon"));
                                returnJson.put("gpsEquipment",json.getString("deviceid"));
                                VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(json.getString("deviceid"));

                                Double goodWeight = vehicleVoMapper.getVehicleGpalOrder(vehicleGpalInfoVo.getVehicleId());

                                if(goodWeight!=null && goodWeight>0){
                                    returnJson.put("taskState","1");
                                }else {
                                    returnJson.put("taskState","0");
                                }
                                returnJson.put("vehicleNum",vehicleGpalInfoVo.getVehicleNum());
                                jsonArray.add(returnJson);
                            }
                        }
                    }
                }
            }
        }
        return jsonArray;
    }

    @Override
    public JSONArray companyVehicleListPosition(String goodsTypae, String goodsSubTypae, String vehicleState,String areaCode) {
        User u = securityUtil.getCurrUser();

        JSONArray jsonArray = new JSONArray();
        String [] goodsSubTypaes = null;
        if(goodsSubTypae!=null && !goodsSubTypae.equals("")){
            goodsSubTypaes = goodsSubTypae.split(",");
        }
        List gpsList = vehicleVoMapper.companyVehicleListPosition(goodsTypae, goodsSubTypaes, vehicleState, u.getId());

        Area area = null;
        if(areaCode!=null && !areaCode.equals("")){
            area = areaCityMapper.getAreaData(areaCode);
        }

        if(gpsList!=null&&gpsList.size()>0){
            JSONObject data = new JSONObject();
            data.put("deviceids",gpsList);
            data.put("lastquerypositiontime",0);
            JSONObject requestJson = gpsUtil.gpsPost(data,"action=lastposition&",redisTemplate);
            if(requestJson!=null && requestJson.getInteger("status")==0){
                JSONArray recordsArray = requestJson.getJSONArray("records");
                if(recordsArray!=null&&recordsArray.size()>0){
                    for (int i = 0; i< recordsArray.size(); i++) {
                        JSONObject json = recordsArray.getJSONObject(i);
                        if(area ==null){
                            JSONObject returnJson = new JSONObject();
                            returnJson.put("lat",json.getDouble("callat"));
                            returnJson.put("lon",json.getDouble("callon"));
                            returnJson.put("gpsEquipment",json.getString("deviceid"));
                            VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(json.getString("deviceid"));

                            Double goodWeight = vehicleVoMapper.getVehicleGpalOrder(vehicleGpalInfoVo.getVehicleId());

                            if(goodWeight!=null && goodWeight>0){
                                returnJson.put("taskState","1");
                            }else {
                                returnJson.put("taskState","0");
                            }
                            returnJson.put("vehicleNum",vehicleGpalInfoVo.getVehicleNum());
                            jsonArray.add(returnJson);

                        }else {
                            double callat = json.getDouble("callat");
                            double callon = json.getDouble("callon");
                            boolean b =distanceCalculation(Double.valueOf(area.getLat()),Double.valueOf(area.getLng()),callat,callon,100000);
                            if(b){
                                JSONObject returnJson = new JSONObject();
                                returnJson.put("lat",json.getDouble("callat"));
                                returnJson.put("lon",json.getDouble("callon"));
                                returnJson.put("gpsEquipment",json.getString("deviceid"));
                                VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(json.getString("deviceid"));

                                Double goodWeight = vehicleVoMapper.getVehicleGpalOrder(vehicleGpalInfoVo.getVehicleId());

                                if(goodWeight!=null && goodWeight>0){
                                    returnJson.put("taskState","1");
                                }else {
                                    returnJson.put("taskState","0");
                                }
                                returnJson.put("vehicleNum",vehicleGpalInfoVo.getVehicleNum());
                                jsonArray.add(returnJson);
                            }
                        }
                    }
                }
            }
        }


        return jsonArray;
    }

    @Override
    public JSONArray vehicleListPosition(String goodsTypae, String goodsSubTypae, String vehicleState,String areaCode) {
        JSONArray jsonArray = new JSONArray();
        String [] goodsSubTypaes = null;
        if(goodsSubTypae!=null && !goodsSubTypae.equals("")){
            goodsSubTypaes = goodsSubTypae.split(",");
        }
        List gpsList = vehicleVoMapper.vehicleGoodsType(goodsTypae, goodsSubTypaes, vehicleState);

        Area area = null;
        if(areaCode!=null && !areaCode.equals("")){
            area = areaCityMapper.getAreaData(areaCode);
        }

        if(gpsList!=null&&gpsList.size()>0){
            JSONObject data = new JSONObject();
            data.put("deviceids",gpsList);
            data.put("lastquerypositiontime",0);
            JSONObject requestJson = gpsUtil.gpsPost(data,"action=lastposition&",redisTemplate);
            if(requestJson!=null && requestJson.getInteger("status")==0){
                JSONArray recordsArray = requestJson.getJSONArray("records");
                if(recordsArray!=null&&recordsArray.size()>0){
                    for (int i = 0; i< recordsArray.size(); i++) {
                        JSONObject json = recordsArray.getJSONObject(i);
                        if(area ==null){
                            JSONObject returnJson = new JSONObject();
                            returnJson.put("lat",json.getDouble("callat"));
                            returnJson.put("lon",json.getDouble("callon"));
                            returnJson.put("gpsEquipment",json.getString("deviceid"));

                            VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(json.getString("deviceid"));

                            Double goodWeight = vehicleVoMapper.getVehicleGpalOrder(vehicleGpalInfoVo.getVehicleId());

                            if(goodWeight!=null && goodWeight>0){
                                returnJson.put("taskState","1");
                            }else {
                                returnJson.put("taskState","0");
                            }

                            returnJson.put("vehicleNum",vehicleGpalInfoVo.getVehicleNum());
                            jsonArray.add(returnJson);

                        }else {
                            double callat = json.getDouble("callat");
                            double callon = json.getDouble("callon");
                            boolean b =distanceCalculation(Double.valueOf(area.getLat()),Double.valueOf(area.getLng()),callat,callon,100000);
                            if(b){
                                JSONObject returnJson = new JSONObject();
                                returnJson.put("lat",json.getDouble("callat"));
                                returnJson.put("lon",json.getDouble("callon"));
                                returnJson.put("gpsEquipment",json.getString("deviceid"));
                                VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(json.getString("deviceid"));

                                Double goodWeight = vehicleVoMapper.getVehicleGpalOrder(vehicleGpalInfoVo.getVehicleId());

                                if(goodWeight!=null && goodWeight>0){
                                    returnJson.put("taskState","1");
                                }else {
                                    returnJson.put("taskState","0");
                                }
                                returnJson.put("vehicleNum",vehicleGpalInfoVo.getVehicleNum());
                                jsonArray.add(returnJson);
                            }
                        }
                    }
                }
            }
        }


        return jsonArray;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    public static boolean distanceCalculation(double radLat1,double radLng1,double radLat2,double radLng2,double range){
        //判断是否在允许范围内

        radLat1 = rad(radLat1);
        radLat2 = rad(radLat2);
        double a = radLat1 - radLat2;
        double b = rad(radLng1) - rad(radLng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
                Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 1000);
        log.info(String.valueOf(s));
        if (s > range){
            return false;
        }else {
            return true;
        }
    }

    public static void main(String[] args) {
        //判断是否在允许范围内

        double radLat1 = rad(39.1286);
        double radLat2 = rad(39.1231);
        double a = radLat1 - radLat2;
        double b = rad(117.249) - rad(117.267);

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
             Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s * EARTH_RADIUS;
        System.out.println(s);
        s = Math.round(s * 1000);
        log.info(String.valueOf(s));
       System.out.println(s);
    }

    @Override
    public Map getOrderProvinceVo(String orderNo) {
        User user =securityUtil.getCurrUser();
        Map map=new HashMap();
        if(orderNo!=null && !orderNo.equals("")){
            OrderProvinceVo orderOrderNo = orderMainMapper.getOrderProvinceorderNoVo(orderNo);
            if(orderOrderNo != null){
                areaAddressUtil.fillAreaAddress(orderOrderNo);
            }
            map.put("orderOrderNo",orderOrderNo);
        }else {
            map.put("orderOrderNo",null);
        }
        OrderProvinceVo orderUserId = orderMainMapper.getOrderProvinceVo(user.getId());

        if(orderUserId != null){
            areaAddressUtil.fillAreaAddress(orderUserId);
        }
        map.put("orderUserId",orderUserId);
        return map;
    }

    @Override
    public OrderProvinceVo addMobileTrack(Long orderId, String lat, String lon, String mobileModel) {
        User user =securityUtil.getCurrUser();
        OrderProvinceVo orderProvinceVo = orderMainMapper.getOrderProvinceState(orderId);

        if(orderProvinceVo!=null){
            MobileTrack mobileTrack = new MobileTrack();
            mobileTrack.setLat(lat);
            mobileTrack.setLon(lon);
            mobileTrack.setDriverUserId(Long.valueOf(orderProvinceVo.getDriverUserId()));
            mobileTrack.setOrderId(orderId);
            mobileTrack.setVehicleLicenseId(orderProvinceVo.getVehicleId());
            mobileTrack.setOrderState(3);
            mobileTrack.setMobileModel(mobileModel);
            mobileTrackDao.save(mobileTrack);
        }
        if(orderProvinceVo != null){
            areaAddressUtil.fillAreaAddress(orderProvinceVo);
        }
        return orderProvinceVo;
    }



    /**
     * 添加运单状态流转记录
     */
    @Override
    public void circulationRecord(String content,Long operationId) {

        Documentary documentary=new Documentary();
        documentary.setOperationId(operationId);
        documentary.setContent(content);
        documentary.setType("2");
        documentary.setOperationType("2");
        documentaryDao.save(documentary);

    }

    @Override
    public void addDocumentary(DocumentaryDto documentaryDto) {

        securityUtil.getCurrUser();
        Documentary documentary=new Documentary();
        ObjectUtil.copyPropertiesIgnoreNull(documentaryDto,documentary);
        documentary.setType("2");
        documentaryDao.save(documentary);

    }





    @Override
    public Page<OrderOrder> findByCondition(OrderOrder orderOrder, SearchVo searchVo, Pageable pageable) {

        return orderOrderDao.findAll(new Specification<OrderOrder>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<OrderOrder> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Date> createTimeField = root.get("createTime");

                List<Predicate> list = new ArrayList<>();

                // 创建时间
                if (StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) {
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }


    @Override
    public String changeOrderState(OrderStatusDto orderStatusDto) {
        User u = securityUtil.getCurrUser();
        OrderOrder order = orderOrderDao.getOne(orderStatusDto.getOrderId());

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (order == null) {
            throw new FreightException("订单不存在");
        } else {
            String res = "操作成功";
            String logContent = "";
            // 订单取消
            if (orderStatusDto.getState().equals(OrderStatusEnum.ORDER_CANCEL.getCode())) {

//                if(order.getOrderState()==0 || order.getOrderState()==1){
                    order.setOrderState(orderStatusDto.getState());
                    order.setOrderStateDesc(orderStatusDto.getDesc());
//                }else {
//                    throw new FreightException("此运单不能被取消");
//                }

                OrderGoods orderGoods=orderGoodsDao.getOne(order.getGoodsId());
                OrderExtend orderExtend = orderExtendDao.findByOrderId(orderStatusDto.getOrderId());
                List<GoodsLoadingTime> goodsLoadingList = orderGoodsVoMapper.getGoodsLoadingOrder(order.getGoodsId(),orderExtend.getEstimateLoadingTime());
                if(goodsLoadingList!=null && goodsLoadingList.size()>0){
                    GoodsLoadingTime goodsLoadingTime = goodsLoadingList.get(0);
                    goodsLoadingTime.setLoadingState("1");
                    goodsLoadingTimeDao.save(goodsLoadingTime);
                }

                orderGoods.setGoodWeight(orderGoods.getGoodWeight()+order.getGoodWeight());
                orderGoods.setStatus(3);
                orderGoodsDao.save(orderGoods);
                logContent = "运单取消";
            } else {

                if(orderStatusDto.getState()==1){
                    Date date=new Date();
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(date);
                    OrderExtend orderExtend = orderExtendDao.findByOrderId(orderStatusDto.getOrderId());
                    orderExtend.setMeetLat(orderStatusDto.getLat());
                    orderExtend.setMeetLng(orderStatusDto.getLng());
                    orderExtendDao.save(orderExtend);
                    logContent = "司机接单";
                }
                if(orderStatusDto.getState()==3&&order.getOrderState()==4){
                    logContent = "运单撤回，重新审核";
                }
                if(orderStatusDto.getState()==4){
                    logContent = "运单审核通过";
                }
                if(orderStatusDto.getState()==5){
                    logContent = "支付运单运费";
                }

                order.setOrderStateDesc(OrderStatusEnum.getName(orderStatusDto.getState()));
                order.setOrderState(orderStatusDto.getState());
            }
            orderOrderDao.save(order);

            //操作记录
            operationLogService.saveOperationLog(6,logContent,order.getId().toString());

            return res;
        }
    }

    public boolean isChangePri(User u, Integer state) {
        OrderStatusEnum statusEnum = OrderStatusEnum.findByCode(state);
        boolean isOk = true;
        switch (statusEnum) {
            case ORDER_CONFIRM:
            case ORDER_COMPANY_SETTLE:
            case ORDER_TRANS:
            case ORDER_COMPANY_PAY:
                if (!UserDtoUtils.isAdminOrDriver(u)) {
                    isOk = false;
                }
                break;
            case ORDER_DRIVER_SETTLE:
            case ORDER_PLAT_SETTLE:
                if (!UserDtoUtils.isAdminOrCompany(u)) {
                    isOk = false;
                }
                break;
            case ORDER_OVER:
                if (!UserDtoUtils.isAdmin(u)) {
                    isOk = false;
                }
                break;
            default:
                isOk = true;
        }
        return isOk;
        // 0   4  6  货主
        // 1 2 3  5  司机
        // 7 平台
    }


    @Override
    public OrderOrder getByGoodId(Long goodId) {
        return orderOrderDao.getByGoodsId(goodId);
    }

    @Override
    public OrderOrder getByOrderNo(String orderNo) {
        return orderOrderDao.getByOrderNo(orderNo);
    }

    @Override
    public void genOrder(PcQuotationDto pcQuotationDto) {
        User u = securityUtil.getCurrUser();
        if (!u.getUserType().equals(CommonConstant.USER_TYPE_COMPANY) && !u.getUserType().equals(CommonConstant.USER_TYPE_ADMIN)) {
            throw new FreightException("请先登入或者切换货主账号生成订单");
        }
        QuotationRecord quotationRecord=quotationRecordDao.getOne(pcQuotationDto.getQuotationRecordId());
        OrderGoods orderGoods=orderGoodsDao.getOne(quotationRecord.getOrderGoodsId());


        List<QuotationDetails> details=quotationRecordMapper.getQuotationDetails(quotationRecord.getId());
        if(details == null || details.size()==0){
            throw new FreightException("操作出错");
        }
        QuotationDetails quotationDetails = details.get(0);
        if(orderGoods.getStatus() != 3){
            throw new FreightException("订单该状态下无法操作");
        }
        //判断订单剩余重量和司机承运重量
        if (orderGoods.getGoodWeight()<quotationDetails.getTransGoodWeight()){
            throw new FreightException("货物不足");
        }
        List<Long> list=orderMainMapper.getHangintheairOrder(quotationRecord.getUserId());
        if (list!=null && list.size()!=0) {
            throw new FreightException("当前司机有未完成订单，不可委托");
        }
        quotationRecord.setDriverState("2");
        OrderOrder orderOrder = new OrderOrder();
        ObjectUtil.copyPropertiesIgnoreNull(orderGoods,orderOrder);
        orderOrder.setDriverTotalPrice(quotationDetails.getFreightTotalPrice());
        orderOrder.setDriverUnitPrice(quotationDetails.getFreightUnitPrice());

        DriverUser driverUser = driverVoMapper.getDriverVoUserId(quotationRecord.getUserId());
        if(driverUser!=null && driverUser.getVehicleId()!=null){
            Long vehicleId = driverUser.getVehicleId();

            VehicleLicense vehicleLicense=vehicleLicenseDao.getOne(vehicleId);



            orderOrder.setVehicleId(vehicleId);
        }

        orderOrder.setCompanyUserId(orderGoods.getCompanyUserId());
        orderOrder.setGoodsId(quotationRecord.getOrderGoodsId());
        orderOrder.setDriverUserId(quotationRecord.getUserId());
        orderOrder.setGoodWeight(quotationDetails.getTransGoodWeight());
        orderOrder.setTransGoodWeight(null);
        orderOrder.setRealGoodWeight(null);
        orderOrder.setOrderSource("1");
        orderGoods.setGoodWeight(orderGoods.getGoodWeight()-quotationDetails.getTransGoodWeight());
        if(orderGoods.getGoodWeight() == 0.0 ){
            orderGoods.setStatus(5);
        }
        orderGoodsDao.save(orderGoods);
        orderOrder.setOrderState(0);
        orderOrder.setOrderStateDesc("待司机接单");
        orderOrder.setId(null);
        orderOrder=orderOrderDao.save(orderOrder);
        quotationRecord.setOrderId(orderOrder.getId());
        quotationRecordDao.save(quotationRecord);
    }





    @Override
    public String uploadReceiptOrderPicId(MultipartFile file, String orderPicType, Long orderId, String address,Double lng,Double lat) {
        User user = securityUtil.getCurrUser();
        OrderOrder order = orderOrderDao.getOne(orderId);
        String mes = "您还未到达指定装货地点，请到达后操作";
        if (orderPicType.equals(FileConstant.ORDER_DELIVERY_PIC)) {
        } else {
            mes = "您还未到达指定卸货地点，请到达后操作";
        }
        if(order.getAddressFence()!=null&&order.getAddressFence().equals("1")){
            //判断是否在允许范围内
            double radLat1 = rad(lat);
            double radLat2 = rad(order.getBeginLat());
            double a = radLat1 - radLat2;
            double b = rad(lng) - rad(order.getBeginLng());
            double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
                    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
            s = s * EARTH_RADIUS;
            s = Math.round(s * 1000);
            log.info(String.valueOf(s));
            if (s > (order.getPretendEnclosure() * 1000)){
                throw new FreightException(mes);
            }
        }
        com.freight.file.entity.File sfile;
            if (order != null) {
                if (orderPicType.equals(FileConstant.ORDER_DELIVERY_PIC)) {
                    sfile =fileService.saveFileByUserId(file,FileConstant.ORDER_DELIVERY_PIC);
                    order.setDeliveryOrderPicId(sfile.getUrl());
                } else {
                    sfile =fileService.saveFileByUserId(file,FileConstant.ORDER_RECEIPT_PIC);
                    order.setReceiptOrderPicId(sfile.getUrl());
                }
                orderOrderDao.save(order);
            } else {
                throw new FreightException("订单异常");
            }

        return sfile.getUrl();
    }

    @Override
    public void updateStatisticsDetails(String types,Long orderId,  Double transGoodWeight, Double realGoodWeight,  BigDecimal driverUnitPrice,
                                        BigDecimal platformUnitPrice,BigDecimal oilcostCargo,BigDecimal etcCargo,
                                        BigDecimal cargoDamage, BigDecimal shouldKnot,BigDecimal solidKnot,BigDecimal adjustment,String addReduce,
                                        String adjustmentremarks,
                                        BigDecimal cargoOwnerAdjustment,String cargoOwnerAddReduce,String cargoOwnerAdjustmentremarks) {
        if (orderId == null){
            throw new FreightException("运单id不能为空");
        }
        OrderOrder orderOrder = get(orderId);
        VehicleLicense vehicleLicense=vehicleLicenseDao.getOne(orderOrder.getVehicleId());

        if (transGoodWeight == null){
            throw new FreightException("装车重量能为空");
        }else {
            orderOrder.setTransGoodWeight(transGoodWeight);

        }
        if (realGoodWeight == null){
            throw new FreightException("卸车重量能为空");
        }else {
            orderOrder.setRealGoodWeight(realGoodWeight);

        }

        if (driverUnitPrice != null){
            orderOrder.setDriverUnitPrice(driverUnitPrice);
        }

        orderOrderDao.save(orderOrder);
    }

    @Override
    public List<Documentary> getDocumentaryList( Long orderId) {
        User user=securityUtil.getCurrUser();

        return orderEntrustedMapper.getDocumentaryList(orderId,"2");
    }

    @Override
    public String uploadOrderInfo(OrderAmtDto orderInfoDto) {
        OrderOrder orderOrder = orderOrderDao.getOne(orderInfoDto.getOrderId());

        if(orderInfoDto.getTransGoodWeight()!=null){
            orderOrder.setTransGoodWeight(orderInfoDto.getTransGoodWeight());
        }
        if(orderInfoDto.getRealGoodWeight()!=null){
            orderOrder.setRealGoodWeight(orderInfoDto.getRealGoodWeight());
        }
        if(orderInfoDto.getRealGoodWeight()>orderInfoDto.getTransGoodWeight()){
            BigDecimal b1 = new BigDecimal(orderInfoDto.getTransGoodWeight().toString());
            orderOrder.setDriverTotalPrice(b1.multiply(orderOrder.getDriverUnitPrice()));
        }else{
            BigDecimal b1 = new BigDecimal(orderInfoDto.getRealGoodWeight().toString());
            orderOrder.setDriverTotalPrice(b1.multiply(orderOrder.getDriverUnitPrice()));
        }
        orderOrderDao.save(orderOrder);
        return "更新成功";
    }


    @Override
    public List<OrderOrder> getOrderByIds(Long[] orderIds) {
        return orderOrderDao.getByIdIn(orderIds);
    }

    @Override
    public List<OrderStateCntVo> getUserOrderCntVo() {
        User u = securityUtil.getCurrUser();

        if (UserDtoUtils.isAdmin(u)) {
            List<OrderStateCntVo> res = orderOrderDao.getCompanyOrderStateCnt();
            for (OrderStateCntVo re : res) {
                re.setStateDesc(OrderStatusEnum.getName(re.getOrderState()));
            }
            return res;
        } else {
            return null;
        }
    }
}